import matplotlib.pyplot as plt
import numpy as np

# 中文显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei','DV Sans']
plt.rcParams['axes.unicode_minus'] = False

# 挑战2：绘制函数证明三次多项式必有实根
def challenge2():
    # 三次多项式至少有一个实根
    x = np.linspace(-3, 3, 1000)
    f = lambda x: x**3 - 2*x + 1  # 任意三次多项式
    
    plt.figure(figsize=(10, 6))
    plt.plot(x, f(x), 'b-', linewidth=2, label='f(x) = x³ - 2x + 1')
    plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)
    
    # 验证存在实根
    roots = []
    for i in range(len(x)-1):
        if f(x[i]) * f(x[i+1]) <= 0:
            root = x[i] - f(x[i]) * (x[i+1] - x[i]) / (f(x[i+1]) - f(x[i]))
            roots.append(root)
            plt.scatter([root], [0], color='red', s=100)
    
    plt.title('挑战2: 三次多项式必有实根')
    plt.xlabel('x'); plt.ylabel('f(x)')
    plt.legend(); plt.grid(True, alpha=0.3)
    plt.show()
    
    print(f"找到实根: {roots}")

challenge2()